package com.pavelkaminsky;


import com.restfb.DefaultFacebookClient;
import com.restfb.DefaultJsonMapper;
import com.restfb.JsonMapper;
import com.restfb.json.JsonObject;
import com.restfb.types.User;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author: Pavel Kaminsky
 * @Site : www.pavel-kaminsky.com
 * @Date: 08/10/11
 */

public class FBClient {

    DefaultFacebookClient facebookClient;

    public FBClient() {
        String accessToken  = ApplicationProperties.getInstance().getProperty("FB.ACCESS_TOKEN");
        facebookClient = new DefaultFacebookClient(accessToken);
    }

    public List<User> getMyFriends() {

        //retreiving all friends facebook IDs
        List<String> ids = new ArrayList<String>();

        for(User friend : facebookClient.fetchConnection("me/friends", User.class).getData())
            ids.add( friend.getId());

        //retreiving all friends fields at once instead of creating an HTTP
        //call for each friend
        JsonObject results = facebookClient.fetchObjects(ids, JsonObject.class);

        //converting bulk result back to java-ish User object
        JsonMapper jsonMapper = new DefaultJsonMapper();
        ArrayList<User> friendsList = new ArrayList<User>();

        for (String id : ids)
            friendsList.add(jsonMapper.toJavaObject(results.getString(id), User.class));

        return friendsList;
    }
}
